package cn.net.autocode.platform.providers.rules;

import cn.hutool.core.util.StrUtil;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.dbManager.SqlWrapper;
import cn.net.autocode.dbManager.SqlWrapperBuilder;
import cn.net.autocode.dbManager.handler.PreparedStatementHandler;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

public class UpdateRules {


    public static void unique(JSONObject rule, JSONObject param, String tableName, Dao dao){
        String columnName = rule.getString("fieldName");
        String fieldName = PreparedStatementHandler.columnToProperty(columnName);
        String matchUl = rule.getString("matchUl");
        SqlWrapperBuilder swb = new SqlWrapperBuilder(tableName);
        swb.selectColumn("count(*)");

        //判断关联字段是否为空
        String refColumn = rule.getString("refColumn");
        if(StrUtil.isNotBlank(refColumn)){
            JSONArray columns = JSONArray.parseArray(refColumn);
            for(int i=0;i<columns.size();i++){
                String refColumnName =  columns.getString(i);
                if (StrUtil.isNotBlank(refColumnName)) {
                    String refFieldName = PreparedStatementHandler.columnToProperty(refColumnName);
                    if (!param.containsKey(refFieldName) || StrUtil.isBlank(param.getString(refFieldName))) {
                        throw new RuntimeException(refColumnName + "不能为空!");
                    }
                    swb.eq(refColumnName, param.get(refFieldName));
                }
            }
        }
        swb.ne("id",param.getString("id"));

        if("U".equals(matchUl)){
            param.put(fieldName,param.getString(fieldName).toUpperCase());
        }else if("L".equals(matchUl)){
            param.put(fieldName,param.getString(fieldName).toLowerCase());
        }
        swb.eq(columnName,param.getString(fieldName));
        SqlWrapper sqlWrapper = swb.sqlWrapper();
        int num = dao.queryValue(sqlWrapper.getSql(), Integer.class,sqlWrapper.getParams().toArray());
        if(num>0){
            String msg = "字段【{}】的值【{}】已存在!";
            msg = StrUtil.format(msg,columnName,param.getString(fieldName));
            throw new RuntimeException(msg);
        }
    }

    public static void required(JSONArray columnsArray, JSONObject param){
        int len = columnsArray.size();
        for(int i=0;i<len;i++){
            JSONObject cj = columnsArray.getJSONObject(i);
            String columnName=cj.getString("name").toLowerCase();
            String fieldName = PreparedStatementHandler.columnToProperty(columnName);

            //必填项校验
            if(!"Y".equals(cj.getString("isnullable"))){
                if(param.containsKey(fieldName) && StrUtil.isBlank(param.getString(fieldName))){
                    throw new RuntimeException(columnName+"不能为空！");
                }
            }
        }
    }



}
